import { AppInfo, ClientRequest } from '../types/index';
import * as fs from 'fs-extra'
import { jobManager, queueManager } from '../manager/index';
import WebServer from '../server/index';
import * as path from 'path';
import { globalEvent, Events } from '../global';

class ClientRequestHandler {
  static resetQueueManagerPause(request: ClientRequest) {
    queueManager.resetPause(request.data)
    return true
  }

  /**
   * 停止整个系统
   * @param request 
   */
  static stopSystem(request: ClientRequest) {
    // TODO
  }

  /**
   * 查找jobs
   * TODO 还未实现
   * @param request 
   */
  static async jobs (request: ClientRequest): Promise<any> {
    return await jobManager.find()
  }
}

function attachEvents () {
  globalEvent.on(Events.WebServer_Request, async (request: ClientRequest) => {
    const method = ClientRequestHandler[request.key]
    if (method) {
      try {
        const res = await method.call(ClientRequestHandler, request)
        globalEvent.emit(Events.WebServer_Response, request.id, res)
      } catch (e) {
        console.error(e)
        globalEvent.emit(Events.WebServer_Response, request.id, {
          success: false,
          message: e.message
        })
      }
    } else {
      globalEvent.emit(Events.WebServer_Response, request.id, {
        success: false,
        message: 'method is not found'
      })
    }
  })
}

export default function Launcher (appInfo: AppInfo) {
  fs.mkdirSync(appInfo.workspace)
  jobManager.init(appInfo.workspace)

  queueManager.loadFromCache(path.join(appInfo.workspace, 'queueCache.json'))
  
  const webServer = new WebServer(appInfo.webUiPort || 3000)

  attachEvents()

  
}